package com.hfut.manage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hfut.manage.pojo.Education;
import com.hfut.manage.pojo.Family;
import com.hfut.manage.pojo.Teacher;
import com.hfut.manage.mapper.TeacherMapper;
import com.hfut.manage.pojo.TeacherDTO;
import com.hfut.manage.service.IEducationService;
import com.hfut.manage.service.IFamilyService;
import com.hfut.manage.service.ITeacherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;


@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements ITeacherService {

    @Autowired
    private IEducationService educationService;

    @Autowired
    private IFamilyService familyService;

    @Autowired
    private TeacherMapper teacherMapper;


    @Override
    @Transactional
    public boolean saveTeahcherDTO(Teacher teacher) {
        return this.saveOrUpdate(teacher);
    }

    public List<Map<String, Object>> getDashDate() {
        return this.teacherMapper.callTeacherStatsProcedure();
    }

    @Override
    @Transactional
    public boolean updateTeacherDTO(Integer id, TeacherDTO teacherDTO) {
        Teacher teacher = new Teacher();
        BeanUtil.copyProperties(teacherDTO, teacher);
        boolean success = updateById(teacher);
        if (!success) {
            return false;
        }

        LambdaQueryWrapper<Education> educationLambdaQueryWrapper = new LambdaQueryWrapper<>();
        educationLambdaQueryWrapper.eq(Education::getTeacherId, id);
        educationService.remove(educationLambdaQueryWrapper);

        LambdaQueryWrapper<Family> familyLambdaQueryWrapper = new LambdaQueryWrapper<>();
        familyLambdaQueryWrapper.eq(Family::getTeacherId, id);
        familyService.remove(familyLambdaQueryWrapper);

        List<Education> educations = teacherDTO.getEducations();
        List<Family> families = teacherDTO.getFamilies();
        educations.forEach(education -> education.setTeacherId(id));
        families.forEach(family -> family.setTeacherId(id));
        educationService.saveBatch(educations);
        familyService.saveBatch(families);
        return true;
    }

    @Override
    public void removeTeacher(Integer id) {
        LambdaQueryWrapper<Teacher> teacherLambdaQueryWrapper = new LambdaQueryWrapper<>();
        teacherLambdaQueryWrapper.eq(Teacher::getId, id);
        this.remove(teacherLambdaQueryWrapper);
        removeById(id);
    }
}
